/*
 * AlbumCoverArtPanel.java
 *
 * Created on October 7, 2008, 9:37 PM
 */
package com.bff.slimserver.musicjukebox.ui;

import com.bff.bjj.utils.Resources.LABEL_KEY;
import com.bff.slimserver.music.MusicObjects;
import com.bff.slimserver.musicjukebox.lib.JukeboxProperties;
import com.bff.slimserver.musicjukebox.ui.components.ArtSizeComboBox;
import com.bff.slimserver.musicjukebox.ui.components.ArtistComboBox;
import com.bff.slimserver.musicjukebox.ui.components.CoverArtPanel;
import com.bff.slimserver.musicjukebox.ui.components.GenreComboBox;
import com.bff.slimserver.musicjukebox.ui.components.YearComboBox;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bff.slimserver.SlimDatabase;
import org.bff.slimserver.exception.SlimConnectionException;
import org.bff.slimserver.musicobjects.SlimAlbum;
import org.bff.slimserver.musicobjects.SlimArtist;
import org.bff.slimserver.musicobjects.SlimGenre;

/**
 * Remember to load this threaded.
 * 
 * @author  Bill
 */
public class AlbumCoverArtPanel extends CoverArtPanel {

    private List<SlimAlbum> albumList;
    private SlimDatabase slimDb;
    private int currentPage;
    private AlbumCoverArtPanel panel;

    /** Creates new form AlbumCoverArtPanel */
    public AlbumCoverArtPanel(Collection<SlimAlbum> albums) {
        try {
            panel = this;

            initComponents();

            currentPage = 0;

            slimDb = JukeboxProperties.getInstance().getDatabase();
            albumList = new ArrayList<SlimAlbum>(albums);

            loadAlbums(currentPage);

        } catch (SlimConnectionException ex) {
            Logger.getLogger(AlbumCoverArtPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void checkYearIndexes() {
        int startYearIndex = cbYearStart.getSelectedIndex();
        if (startYearIndex == 0) {
            setEndYearEnabled(false);
        } else {
            setEndYearEnabled(true);
        }
        int endYearIndex = cbYearEnd.getSelectedIndex();
        if (endYearIndex < startYearIndex) {
            cbYearEnd.setSelectedIndex(startYearIndex);
        }
    }

    private void filter() {
        int startYearIndex = cbYearStart.getSelectedIndex() - 1;
        int endYearIndex = cbYearEnd.getSelectedIndex() - 1;
        SlimGenre genre = ((GenreComboBox) cbGenre).getSelectedGenre();
        SlimArtist artist = ((ArtistComboBox) cbArtist).getSelectedArtist();

        try {
            if (startYearIndex <= 0 && genre == null && artist == null) {
                albumList = new ArrayList<SlimAlbum>(MusicObjects.getAlbums());
            } else {

                if (!cbYearEnd.isEnabled()) {
                    albumList = new ArrayList<SlimAlbum>(slimDb.listAlbums(artist, genre, null));
                } else {
                    List<String> yearList = new ArrayList<String>(((YearComboBox) cbYearStart).getYearList());

                    albumList.clear();
                    for (int i = startYearIndex; i < endYearIndex + 1; i++) {
                        albumList.addAll(slimDb.listAlbums(artist, genre, yearList.get(i)));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        currentPage = 0;
        loadAlbums(currentPage);
    }

    /**
     * 0 based
     * @param page
     */
    private void loadAlbums(int albumPage) {
        if (albumPage < 0) {
            albumPage = 0;
        }

        final int coverArtSize = JukeboxProperties.getInstance().getCoverSize();
        //final int coversPerPage = JukeboxProperties.getInstance().getCoversPerPage();

        final int page = albumPage;

        new Thread(new Runnable() {

            @Override
            public void run() {

                int coversPerPage = getCoversPerPage();

                artPanel.removeAll();
                artPanel.repaint();

                int start = 0;
                int end = 0;

                int pageStart = 0;

                if (page > 0) {
                    pageStart = page * coversPerPage;
                }

                if (pageStart > albumList.size()) {

                    end = albumList.size();
                    start = end - coversPerPage;

                    if (start < 0) {
                        start = 0;
                    }

                } else {
                    start = page * coversPerPage;
                    end = start + coversPerPage;
                    if (end > albumList.size()) {
                        end = albumList.size();
                    }
                }


                for (int i = start; i < end; i++) {
                    AlbumThumbnailPanel thumbPanel = null;

                    //SlimSong song = slimDb.lookupSong(albumList.get(i).getArtworkTrackId());
                    SlimAlbum album = albumList.get(i);
                            thumbPanel = new AlbumThumbnailPanel(album);
                            thumbPanel.setPreferredSize(new Dimension(coverArtSize, coverArtSize));
                        artPanel.add(thumbPanel);
                        thumbPanel.loadImage();
                    }

                //set button availability
                if (albumList.size() < coversPerPage) {
                    //there is only one page
                    btnLast.setEnabled(false);
                    btnNext.setEnabled(false);
                    btnFirst.setEnabled(false);
                    btnPrev.setEnabled(false);
                } else if (currentPage == 0) {
                    btnFirst.setEnabled(false);
                    btnPrev.setEnabled(false);
                    btnNext.setEnabled(true);
                    btnLast.setEnabled(true);
                } else if (currentPage == albumList.size() / coversPerPage) {
                    //we are on the last page
                    btnLast.setEnabled(false);
                    btnNext.setEnabled(false);
                    btnFirst.setEnabled(true);
                    btnPrev.setEnabled(true);
                } else {
                    btnLast.setEnabled(true);
                    btnNext.setEnabled(true);
                    btnFirst.setEnabled(true);
                    btnPrev.setEnabled(true);
                }
            }
        }).start();

        currentPage = page;
    }

    private int getCoversPerPage() {
        while (panel.getSize().getHeight() < 1) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
                Logger.getLogger(AlbumCoverArtPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        int rows = (int) (panel.getSize().getHeight() - 200) / JukeboxProperties.getInstance().getCoverSize();
        int cols = (int) (panel.getSize().getWidth()) / JukeboxProperties.getInstance().getCoverSize();

        return cols * rows;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        spAlbums = new javax.swing.JScrollPane();
        artPanel = new CoverArtPanel();
        artPanel.setLayout(new WrapLayout());
        bottomPanel = new javax.swing.JPanel();
        btnPanel = new javax.swing.JPanel();
        btnFirst = new com.bff.bjj.ui.component.BJJButton();
        btnPrev = new com.bff.bjj.ui.component.BJJButton();
        btnNext = new com.bff.bjj.ui.component.BJJButton();
        btnLast = new com.bff.bjj.ui.component.BJJButton();
        jLabel5 = new javax.swing.JLabel();
        cbSize = new ArtSizeComboBox();
        cbSize.setSelectedItem(JukeboxProperties.getInstance().getCoverSize());
        filterPanel = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        cbArtist = new ArtistComboBox();
        jLabel1 = new javax.swing.JLabel();
        cbYearStart = new YearComboBox();
        jLabel3 = new javax.swing.JLabel();
        cbYearEnd = new YearComboBox();
        jLabel2 = new javax.swing.JLabel();
        cbGenre = new GenreComboBox();
        btnFilter = new com.bff.bjj.ui.component.BJJButton();
        btnReset = new com.bff.bjj.ui.component.BJJButton();

        setLayout(new java.awt.BorderLayout());

        spAlbums.setHorizontalScrollBar(null);
        spAlbums.setViewportView(artPanel);

        add(spAlbums, java.awt.BorderLayout.CENTER);

        bottomPanel.setLayout(new java.awt.BorderLayout());

        btnFirst.setText(getResource(LABEL_KEY.ALBUM_FILTER_BUTTON_FIRST_LABEL));
        btnFirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFirstActionPerformed(evt);
            }
        });
        btnPanel.add(btnFirst);

        btnPrev.setText(getResource(LABEL_KEY.ALBUM_FILTER_BUTTON_PREV_LABEL));
        btnPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrevActionPerformed(evt);
            }
        });
        btnPanel.add(btnPrev);

        btnNext.setText(getResource(LABEL_KEY.ALBUM_FILTER_BUTTON_NEXT_LABEL));
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });
        btnPanel.add(btnNext);

        btnLast.setText(getResource(LABEL_KEY.ALBUM_FILTER_BUTTON_LAST_LABEL));
        btnLast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLastActionPerformed(evt);
            }
        });
        btnPanel.add(btnLast);

        jLabel5.setText(getResource(LABEL_KEY.ALBUM_FILTER_COVER_SIZE));
        btnPanel.add(jLabel5);

        cbSize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbSizeActionPerformed(evt);
            }
        });
        btnPanel.add(cbSize);

        bottomPanel.add(btnPanel, java.awt.BorderLayout.NORTH);

        jLabel4.setText(getResource(LABEL_KEY.ALBUM_FILTER_ARTIST));
        filterPanel.add(jLabel4);

        cbArtist.setMaximumSize(new java.awt.Dimension(300, 32767));
        cbArtist.setPreferredSize(new java.awt.Dimension(200, 27));
        filterPanel.add(cbArtist);

        jLabel1.setText(getResource(LABEL_KEY.ALBUM_FILTER_START_YEAR));
        filterPanel.add(jLabel1);

        cbYearStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbYearStartActionPerformed(evt);
            }
        });
        filterPanel.add(cbYearStart);

        jLabel3.setText(getResource(LABEL_KEY.ALBUM_FILTER_END_YEAR));
        jLabel3.setEnabled(false);
        filterPanel.add(jLabel3);

        cbYearEnd.setEnabled(false);
        cbYearEnd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbYearEndActionPerformed(evt);
            }
        });
        filterPanel.add(cbYearEnd);

        jLabel2.setText(getResource(LABEL_KEY.ALBUM_FILTER_GENRE));
        filterPanel.add(jLabel2);
        filterPanel.add(cbGenre);

        btnFilter.setText(getResource(LABEL_KEY.ALBUM_FILTER_BUTTON_LABEL));
        btnFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFilterActionPerformed(evt);
            }
        });
        filterPanel.add(btnFilter);

        btnReset.setText(getResource(LABEL_KEY.ALBUM_FILTER_RESET_BUTTON_LABEL));
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });
        filterPanel.add(btnReset);

        bottomPanel.add(filterPanel, java.awt.BorderLayout.SOUTH);

        add(bottomPanel, java.awt.BorderLayout.SOUTH);
    }// </editor-fold>//GEN-END:initComponents

private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
    loadAlbums(++currentPage);
}//GEN-LAST:event_btnNextActionPerformed

private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirstActionPerformed
    loadAlbums(0);
}//GEN-LAST:event_btnFirstActionPerformed

private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLastActionPerformed
    loadAlbums(albumList.size() / getCoversPerPage());
}//GEN-LAST:event_btnLastActionPerformed

private void btnPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrevActionPerformed
    loadAlbums(--currentPage);
}//GEN-LAST:event_btnPrevActionPerformed

private void cbYearStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbYearStartActionPerformed
    checkYearIndexes();
}//GEN-LAST:event_cbYearStartActionPerformed

private void btnFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFilterActionPerformed
    filter();
}//GEN-LAST:event_btnFilterActionPerformed

private void cbYearEndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbYearEndActionPerformed
    checkYearIndexes();
}//GEN-LAST:event_cbYearEndActionPerformed

private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
    cbGenre.setSelectedIndex(0);
    cbYearEnd.setSelectedIndex(0);
    cbYearStart.setSelectedIndex(0);
    cbArtist.setSelectedIndex(0);
    filter();
}//GEN-LAST:event_btnResetActionPerformed

private void cbSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSizeActionPerformed
    int size = ((ArtSizeComboBox) cbSize).getSelectedSize();

    JukeboxProperties.getInstance().setCoverSize(size);
    loadAlbums(currentPage);
}//GEN-LAST:event_cbSizeActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel artPanel;
    private javax.swing.JPanel bottomPanel;
    private javax.swing.JButton btnFilter;
    private javax.swing.JButton btnFirst;
    private javax.swing.JButton btnLast;
    private javax.swing.JButton btnNext;
    private javax.swing.JPanel btnPanel;
    private javax.swing.JButton btnPrev;
    private javax.swing.JButton btnReset;
    private javax.swing.JComboBox cbArtist;
    private javax.swing.JComboBox cbGenre;
    private javax.swing.JComboBox cbSize;
    private javax.swing.JComboBox cbYearEnd;
    private javax.swing.JComboBox cbYearStart;
    private javax.swing.JPanel filterPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane spAlbums;
    // End of variables declaration//GEN-END:variables

    private void setEndYearEnabled(boolean b) {
        jLabel3.setEnabled(b);
        cbYearEnd.setEnabled(b);
    }
}
